package com.michaeliu.flutter.study.flutter_sample

import android.content.Context
import android.util.Log
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel

class TestMethodChannel(context : Context, messenger: BinaryMessenger) : MethodChannel.MethodCallHandler {

    private lateinit var mChannel : MethodChannel

    companion object {
        private const val CHANNEL_NAME = "com.michaeliu.flutter.study/method_channel"
    }

    init {
        initChannel(messenger)
    }

    private fun initChannel(messenger: BinaryMessenger) {
        mChannel = MethodChannel(messenger, CHANNEL_NAME)
        mChannel.setMethodCallHandler(this)
    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        Log.i("liuguoquan", call.method)
        val methodName = call.method
        when(methodName) {
            "send" -> {
                result.success("Android端接收 Flutter端 send 请求成功")
                mChannel.invokeMethod("sendToFlutter", null,object : MethodChannel.Result{
                    override fun success(result: Any?) {
                        Log.i("liuguoquan", "$result")
                    }

                    override fun error(
                        errorCode: String,
                        errorMessage: String?,
                        errorDetails: Any?
                    ) {

                    }

                    override fun notImplemented() {

                    }

                })
            }
            "get" -> {
                result.success("Android端接收Flutter端GET请求成功")
                mChannel.invokeMethod("getFromFlutter", null, object : MethodChannel.Result {
                    override fun success(result: Any?) {
                        Log.i("liuguoquan", "$result")
                    }

                    override fun error(
                        errorCode: String,
                        errorMessage: String?,
                        errorDetails: Any?
                    ) {

                    }

                    override fun notImplemented() {

                    }
                })
            }
            else -> {
                result.notImplemented()
            }
        }
    }

}